import _ from 'lodash'
export function isQyWxBrowser() {
	const userAgent = navigator.userAgent
	return userAgent.includes('wxwork')
}

export function isSimple(obj) {
	return typeof obj !== 'object' || obj === null
}

export function isComplex(obj) {
	return typeof obj === 'object' && obj !== null
}

// 精确获取类型
export function exactType(obj) {
	return Object.prototype.toString.call(obj).slice(8, -1)
}

// 对象属性转为驼峰写法
export const camelCase = function (obj) {
	const temp = {}
	Object.getOwnPropertyNames(obj).forEach((key) => {
		let val = obj[key]
		key = _.camelCase(key)
		temp[key] = val
	})
	return temp
}

// 驼峰改下划线
export function transformKey(obj) {
	const isSingle = [
		'String',
		'Number',
		'Function',
		'Null',
		'Undefined'
	].includes(Object.prototype.toString.call(obj).slice(8, -1))

	if (isSingle) {
		return obj
	}
	const res = {}
	Object.keys(obj).forEach((key) => {
		if (!key.includes('_')) {
			const arr = key.split('')
			const newKey = arr.reduce((pre, a) => {
				if (a != a.toLowerCase()) {
					a = '_' + a.toLowerCase()
				}
				return pre + a
			}, '')
			res[newKey] = obj[key]
		} else {
			res[key] = obj[key]
		}
	})
	return res
}

// 计算年龄
export const getAgeByNo = (no = '') => {
	if (!no) return no
	const toStr = no.toString()
	const birth = getBirth(toStr)
	return getAgeByBirth(birth)
}
// 计算生日
export const getBirth = (
	no = '',
	slipt = '-',
	isDate = false,
	isRreverse = false
) => {
	if (!no) return no
	const toStr = no.toString()
	const yearStr = toStr.substring(6, 10)
	const dateStr = `${toStr.substring(10, 12)}${slipt}${toStr.substring(12, 14)}`
	const reulst = isDate ? dateStr : `${yearStr}${slipt}${dateStr}`
	return isRreverse ? reulst.split(slipt).reverse().join(slipt) : reulst
}

export function getAgeByBirth(birthStr) {
	const birth = new Date(birthStr)
	const today = new Date()
	let age = today.getFullYear() - birth.getFullYear()
	if (
		today.getMonth() < birth.getMonth() ||
		(today.getMonth() == birth.getMonth() && today.getDate() < birth.getDate())
	) {
		age--
	}
	return age
}
/** 深拷贝 */
export function objDeepCopy(source) {
	if (isSimple(source)) return source
	var sourceCopy = source instanceof Array ? [] : {}
	for (var item in source) {
		if (!source[item]) {
			sourceCopy[item] = source[item]
		} else {
			sourceCopy[item] = objDeepCopy(source[item])
		}
	}
	return sourceCopy
}

/** 获取file大小的名称 */
export function fileSize(size) {
	var size_int = size
	if (typeof size === 'string' && size.constructor == String) {
		size_int = parseInt(size)
	}
	var formatSize
	if (parseInt(size_int / 1024 / 1024) > 0) {
		formatSize = (size_int / 1024 / 1024).toFixed(2) + 'MB'
	} else if (parseInt(size_int / 1024) > 0) {
		formatSize = (size_int / 1024).toFixed(2) + 'kB'
	} else {
		formatSize = size_int + 'Byte'
	}
	return formatSize
}
